package com.example.city_home_app.Activity;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.city_home_app.Bean.Down_Universe;
import com.example.city_home_app.Bean.Down_UserInfo;
import com.example.city_home_app.Model.ApiModel;
import com.example.city_home_app.R;
import com.example.city_home_app.RetrofitListener;
import com.example.city_home_app.UI.MyCircleImageView;
import com.example.city_home_app.UI.UIUtils;
import com.squareup.picasso.Picasso;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

public class EditActivity extends BaseActivity {
    @BindView(R.id.toolbar_edit)
    Toolbar toolbarEdit;
    @BindView(R.id.img_edit_head)
    MyCircleImageView imgEditHead;
    @BindView(R.id.img_edit_headedit)
    ImageView imgEditHeadedit;
    @BindView(R.id.tv_edit_username)
    TextView tvEditUsername;
    @BindView(R.id.img_edit_nameedit)
    ImageView imgEditNameedit;
    @BindView(R.id.tv_edit_gender)
    TextView tvEditGender;
    @BindView(R.id.img_edit_genderedit)
    ImageView imgEditGenderedit;
    @BindView(R.id.tv_edit_intro)
    TextView tvEditIntro;
    @BindView(R.id.img_edit_introedit)
    ImageView imgEditIntroedit;
    @BindView(R.id.img_edit_passwordedit)
    ImageView imgEditPasswordedit;

    private ApiModel model = new ApiModel();
    private List<Uri> list;

    private RetrofitListener<Down_UserInfo> infolistener = new RetrofitListener<Down_UserInfo>() {
        @Override
        public void onResponse(Down_UserInfo listener) {
            tvEditUsername.setText(listener.getUser_name());
            tvEditIntro.setText(listener.getUser_intro());
            if(listener.getUser_gender()==1){
                tvEditGender.setText("男");
            }else{
                tvEditGender.setText("女");
            }
            Picasso.with(EditActivity.this)
                    .load("http://siminzhang.top:8088/city_home_server/public/static/posters/"+listener.getUser_headimage())
                    .into(imgEditHead);
        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<Down_Universe> listener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if(listener.getMessage().equals("success")){
                UIUtils.showToast(EditActivity.this,"修改成功",UIUtils.LENGTH_SHORT);
                model.getuserinfo(BaseActivity.getUserinfo().getUserid(),infolistener);
            }else{
                UIUtils.showToast(EditActivity.this,listener.getMessage(),UIUtils.LENGTH_SHORT);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_edit;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this);
        showToast();
    }

    @Override
    protected void initData() {
        super.initData();
        model.getuserinfo(BaseActivity.getUserinfo().getUserid(),infolistener);
    }

    private void showToast() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        toolbarEdit = (Toolbar) findViewById(R.id.toolbar_edit);
        setSupportActionBar(toolbarEdit);
        toolbarEdit.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @OnClick({R.id.img_edit_headedit, R.id.img_edit_nameedit, R.id.img_edit_passwordedit, R.id.img_edit_genderedit, R.id.img_edit_introedit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_edit_headedit:
                showimage();
                break;
            case R.id.img_edit_nameedit:
                showeditdialog(0,tvEditUsername.getText().toString());
                break;
            case R.id.img_edit_passwordedit:
                MainActivity.instance.finish();
                if(UserInfoActivity.instance!=null) {
                    UserInfoActivity.instance.finish();
                }
                Intent intent = new Intent(this,ForgotActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
                finish();
                break;
            case R.id.img_edit_genderedit:
                showeditdialog(1,tvEditGender.getText().toString());
                break;
            case R.id.img_edit_introedit:
                showeditdialog(2,tvEditIntro.getText().toString());
                break;
        }
    }

    private void showeditdialog(final int type, final String value) {
        if (type != 1) {
            final BottomDialog dialog;
            dialog = BottomDialog.create(getSupportFragmentManager());
            dialog.setViewListener(new BottomDialog.ViewListener() {
                @Override
                public void bindView(final View v) {
                    final EditText mEditText = (EditText) v.findViewById(R.id.edittext_dialog_newscomment_content);
                    Button button = (Button) v.findViewById(R.id.btn_dialog_newscomment_send);
                    mEditText.post(new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager imm =
                                    (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.showSoftInput(mEditText, 0);
                        }
                    });
                    mEditText.setText(value);
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (!mEditText.getText().toString().equals("")) {
                                update(type,mEditText.getText().toString());
                                dialog.dismiss();
                            } else {
                                UIUtils.showToast(EditActivity.this, "格式非法", UIUtils.LENGTH_SHORT);
                            }
                        }
                    });
                }
            })
                    .setLayoutRes(R.layout.newscomment_dialog)
                    .setDimAmount(0.1f)
                    .setCancelOutside(true)
                    .setTag("修改个人信息")
                    .show();
        }else{
            final BottomDialog dialog;
            dialog = BottomDialog.create(getSupportFragmentManager());
            dialog.setViewListener(new BottomDialog.ViewListener() {
                @Override
                public void bindView(final View v) {
                    final TextView edit = (TextView)v.findViewById(R.id.tv_editdialog_edit);
                    final TextView exit = (TextView)v.findViewById(R.id.tv_editdialog_exit);
                    edit.setText("男");
                    exit.setText("女");
                    edit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            update(1,edit.getText().toString());
                            dialog.dismiss();
                        }
                    });

                    exit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            update(1,exit.getText().toString());
                            dialog.dismiss();
                        }
                    });
                }
            })
                    .setLayoutRes(R.layout.edit_dialog)
                    .setDimAmount(0.1f)
                    .setCancelOutside(true)
                    .setTag("设置")
                    .show();
        }
    }

    private void update(int type,String msg){
        switch (type){
            case 0:
                //昵称
                model.updateusername(BaseActivity.getUserinfo().getUserid(),msg,listener);
                break;
            case 1:
                //性别
                model.updateusergender(BaseActivity.getUserinfo().getUserid(),msg.equals("男")?1:2,listener);
                break;
            case 2:
                //签名
                model.updateuserintro(BaseActivity.getUserinfo().getUserid(),msg,listener);
                break;
        }
    }

    private void showimage(){
        Matisse.from(this)
                .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF))
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .theme(R.style.Matisse_Zhihu)
                .imageEngine(new PicassoEngine())
                .capture(false)
                .forResult(100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 100 && resultCode == RESULT_OK) {
                    list = Matisse.obtainResult(data);
                    String path = UIUtils.getFilePathFromUri(this, list.get(0));
                    model.updateuserhaedimage(BaseActivity.getUserinfo().getUserid(),path,listener);
                }
            }
        }
    }
}
